package com.bjpowernode.listener;

import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

//ServletContext为Tomcat的服务对象，
//ServletContext可以定义全局变量
//ServletContext可以使用ServletContextListener监听其生死
//ServletContext对象一个Tomcat服务只有一个实例
//监听Tomcat服务的启动和销毁
//实现一个接口即可
//注册监听器
@WebListener
public class MyTomcatListener implements ServletContextListener {
    //Tomcat启动监听
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String hzj = servletContext.getInitParameter("hzj");
        System.out.println("Tomcat启动啦：" + hzj);
    }

    //Tomcat销毁监听
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // Your webapp classloader
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        final Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            final Driver driver = drivers.nextElement();
            // We deregister only the classes loaded by this application's classloader
            if (driver.getClass().getClassLoader() == cl) {
                try {
                    DriverManager.deregisterDriver(driver);
                } catch (SQLException e) {
                    System.out.println("JDBC Driver deregistration problem." + e);
                }
            }
        }
        AbandonedConnectionCleanupThread.checkedShutdown();
    }
}
